//
//  FriendListTb.m
//  project
//
//  Created by 黄建华 on 2018/8/9.
//  Copyright © 2018年 黄建华. All rights reserved.
//

#import "FriendListTb.h"
#import "FriendListCell.h"

@implementation FriendListTb

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _tableView                              = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.width, self.height) style:UITableViewStylePlain];
        _tableView.delegate                     = self;
        _tableView.dataSource                   = self;
        _tableView.separatorStyle               = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        [self addSubview:_tableView];
        [self createMjHeader];
    }
    return self;
}

// 下拉刷新
- (void)createMjHeader
{
    _myHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadHeaderData)];
    _myHeader.backgroundColor            = [UIColor colorFromHex:0x4b4b4b];
    _myHeader.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
    // 设置文字
    [_myHeader setTitle:SN_Text(@"下拉刷新") forState:MJRefreshStateIdle];
    [_myHeader setTitle:SN_Text(@"松开刷新") forState:MJRefreshStatePulling];
    [_myHeader setTitle:SN_Text(@"加载 ...") forState:MJRefreshStateRefreshing];
    
    // 设置字体
    _myHeader.stateLabel.font           = [UIFont systemFontOfSize:15];
    _myHeader.lastUpdatedTimeLabel.font = [UIFont systemFontOfSize:14];
    _myHeader.lastUpdatedTimeLabel.text = [NSString stringWithFormat:@"%@:%@", SN_Text(@"上次更新"), [[NSDate date]dateToString]];
    
    // 设置颜色
    _myHeader.stateLabel.textColor           = SNCOLORGRAY;
    _myHeader.lastUpdatedTimeLabel.textColor = SNCOLORGRAY;
    // 设置刷新控件
    _tableView.mj_header                          = _myHeader;
    _tableView.mj_header.automaticallyChangeAlpha = YES;
}

- (void)loadHeaderData {
    NSLog(@"下拉刷新>>>>>>>>");
    [self updateFriendRequest];
    [self endRefreshing:3.0 withTypte:1];
}

- (void)endRefreshing:(CGFloat)time withTypte:(NSInteger)type {
    __unsafe_unretained UITableView *tableView = self.tableView;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 结束刷新
        if (type == 1) {
            [tableView.mj_header endRefreshing];
        }
        else
        {
            [tableView.mj_footer endRefreshing];
        }
    });
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"FriendListTableViewCell";
    FriendListCell  *cell       = [tableView cellForRowAtIndexPath:indexPath];
    
    if (nil == cell) {
        cell = [[FriendListCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
    }
    cell.editButton.tag = indexPath.row + 110000;
    [cell.editButton addTarget:self action:@selector(remarkButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    FriednInviterModel *model = _dataArray[indexPath.row];
    [cell updateCellWithModel:model];
    return cell;
}

////根据宽度求高度  content 计算的内容  width 计算的宽度 font字体大小
//+ (CGFloat)getLabelHeightWithText:(NSString *)text width:(CGFloat)width font: (CGFloat)font
//{
//    CGRect rect = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont ZKYLTFont:font]} context:nil];
//
//    return rect.size.height;
//}

- (void)updateUIViewWith:(NSArray *)listArray
{
//    NSLog(@"更新好友列表>>>>>%@",listArray);
    NSMutableArray *array = [[NSMutableArray alloc] init];
    for (NSDictionary *dicN in listArray) {
        NSDictionary *dic = dicN[@"friend"];
        FriednInviterModel *model = [[FriednInviterModel alloc] init];
        model.userId = [dicN[@"friend_user_id"]integerValue];
        NSString *remark = dicN[@"remark"];
        if (remark.length == 0) {
            remark = SN_Text(@"未填写备注");
        }
        model.remark = remark;
        model.nickName = dic[@"nickname"];
        model.gender = [dic[@"gender"]integerValue];
        model.imagePathUrlString = dic[@"portrait"];
        model.sign = dic[@"sign"];
        NSDictionary *sport = dic[@"sport"];
        NSString *sportDateString = sport[@"today_date"];
        NSString *todayDateString = [[NSDate date]dateToDayString];
        if ([sportDateString isEqualToString:todayDateString]) {
            model.step = [sport[@"step"]integerValue];
            model.distance = [sport[@"distance"]integerValue];
            model.calory = [sport[@"calory"]integerValue];
            model.duration = [sport[@"duration"]integerValue];
        }
        else
        {
            model.step = 0;
            model.distance = 0;
            model.calory = 0;
            model.duration = 0;
        }
        [array addObject:model];
    }
    _dataArray = [NSMutableArray arrayWithArray:array];
    [_tableView reloadData];
}

- (void)updateFriendRequest {
    DEF_WEAKSELF_(FriendListTb)
    [SN_Net friendGetListSuccess:^(id object) {
        NSArray *listArray = object;
        if (listArray) {
            [weakSelf updateUIViewWith:listArray];
        }
    } fail:^(id object) {
    }];
}

//先要设Cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

//定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
     return SN_Text(@"删除");
}

//设置进入编辑状态时，Cell不会缩进
- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}

//点击删除
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    //在这里实现删除操作
    FriednInviterModel *model = _dataArray[indexPath.row];
    
    NSLog(@"要删除的  %@>>>", model.nickName);
    
    [SN_Net friendDeleteFriend:StrByInt(model.userId) Success:^(id object) {
        [self updateFriendRequest];
    } fail:^(id object) {
    }];
    //删除数据，和删除动画
    [_dataArray removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:indexPath.row inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSLog(@"好友列表选择了>>>%d", indexPath.row);
    FriednInviterModel *model = _dataArray[indexPath.row];
    if (_selectFriendBlock) {
        _selectFriendBlock(model);
    }
}

- (void)remarkButtonClick:(UIButton *)sender {
    NSInteger          index  = sender.tag - 110000;
    FriednInviterModel *model = _dataArray[index];
    
    NSLog(@"备注好友:%@", model.nickName);
    
    if (_remarkView) {
        _remarkView = nil;
        [_remarkView removeFromSuperview];
        _remarkView.remarkClickBlock = nil;
    }
    DEF_WEAKSELF_(FriendListTb)
    _remarkView                  = [[FriendRemarkView alloc] initWithFrame:CGRectMake(0, 0, screenWidth - 50, 220) withModel:model];
    _remarkView.remarkClickBlock = ^{
        [weakSelf updateFriendRequest];
    };
    [_remarkView popupWithtype:PopupViewOption_colorLump succeedBlock:^(UIView *View)
     {
         View.center = CGPointMake(kSCREEN_WIDTH/2, kSCREEN_HEIGHT/2);
     }            dismissBlock:^(UIView *View)
     {
     }];
}

@end
